<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- AdThrive Head Tag Manual -->
    <script data-no-optimize="1" data-cfasync="false">
      (function (w, d) {
        w.adthrive = w.adthrive || {};
        w.adthrive.cmd = w.adthrive.cmd || [];
        w.adthrive.plugin = "adthrive-ads-manual";
        w.adthrive.host = "ads.adthrive.com";
        var s = d.createElement("script");
        s.async = true;
        s.referrerpolicy = "no-referrer-when-downgrade";
        s.src =
          "https://" +
          w.adthrive.host +
          "/sites/643436a4e6d20859e40a446b/ads.min.js?referrer=" +
          w.encodeURIComponent(w.location.href) +
          "&cb=" +
          (Math.floor(Math.random() * 100) + 1);
        var n = d.getElementsByTagName("script")[0];
        n.parentNode.insertBefore(s, n);
      })(window, document);
    </script>
    <!-- End of AdThrive Head Tag -->

    <meta charset="utf-8" />
    <title>Drawing axis in d3.js</title>
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, shrink-to-fit=no"
    />
    <meta name="description" content="Drawing axis with d3.js" />
    <meta
      name="keywords"
      content="Data,Dataviz,Datavisualization,Javascript, JS, d3.js, axis, x, y"
    />
    <meta name="author" content="Yan Holtz" />

    <meta property="og:title" content="Drawing axis with d3.js" />
    <meta property="og:image" content="img/overview_RGG.png" />
    <meta property="og:description" content="Using d3.js to draw axis" />

    <!-- Bootstrap core CSS -->
    <link href="../vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet" />

    <!-- Custom fonts for this template -->
    <link
      href="../vendor/font-awesome/css/font-awesome.min.css"
      rel="stylesheet"
      type="text/css"
    />

    <!-- Custom styles for this template -->
    <link href="../css/agency.css" rel="stylesheet" />

    <!-- PRISM -->
    <script src="../LIB/prism.js"></script>
    <link href="../LIB/prism.css" rel="stylesheet" />

    <!-- D3.JS v4 -->
    <script src="../js/d3.v4.js"></script>

    <!-- JQUERY -->
    <script src="../vendor/jquery/jquery.min.js"></script>

    <!-- HTML TO CANVAS -->
    <script src="../js/html2canvas.js"></script>

    <!-- Function to parse html and js code chunks made by Yan Holtz -->
    <script src="../js/myParser.js"></script>
  </head>

  <body id="page-top">
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg fixed-top" id="mainNav">
      <div class="container">
        <a class="js-scroll-trigger" href="../index.html"
          >D3.js Graph Gallery</a
        >
        <button
          class="navbar-toggler navbar-toggler-right"
          type="button"
          data-toggle="collapse"
          data-target="#navbarResponsive"
          aria-controls="navbarResponsive"
          aria-expanded="false"
          aria-label="Toggle navigation"
        >
          Menu
          <i class="fa fa-bars"></i>
        </button>
        <div class="collapse navbar-collapse" id="navbarResponsive">
          <ul class="navbar-nav text-uppercase ml-auto">
            <li class="nav-item">
              <a class="nav-link" href="CONTENT/optimization.html">R</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="CONTENT/private_API.html">Python</a>
            </li>
            <li class="nav-item">
              <a
                class="nav-link js-scroll-trigger"
                href="CONTENT/arbitrage.html"
                >Data to viz</a
              >
            </li>
            <li class="nav-item">
              <a class="nav-link js-scroll-trigger" href="#contact">Who am I</a>
            </li>
            <li class="nav-item">
              <a class="nav-link js-scroll-trigger" href="#contact">About</a>
            </li>
          </ul>
        </div>
      </div>
    </nav>

    <!-- Header -->
    <header class="masthead" style="padding-top: 150px; padding-bottom: 80px">
      <div class="textlanding">
        <p style="display: inline; font-size: 35px">Updating data</p>
        <hr
          style="
            width: 100px;
            height: 1px;
            border: none;
            color: #333;
            background-color: #333;
          "
        />
        <br />
        <ul class="list-inline social-buttons">
          <li class="list-inline-item">
            <a href="https://twitter.com/R_Graph_Gallery">
              <i class="fa fa-twitter"></i>
            </a>
          </li>
          <li class="list-inline-item social-buttons">
            <a href="https://github.com/holtzy">
              <i class="fa fa-github" style="color: white"></i>
            </a>
          </li>
          <li class="list-inline-item social-buttons">
            <a href="https://www.linkedin.com/in/yan-holtz-2477534a/">
              <i class="fa fa-linkedin"></i>
            </a>
          </li>
        </ul>
        <br /><br />
        <p style="max-width: 700px; margin: auto">
          This is document gives a few insights on how to draw axis with the
          d3.js library. It is composed by several interactive examples,
          allowing to play with the code to understand better how it works.
        </p>
      </div>
    </header>

    <!-- ==================== BASIC LINEAR AXIS ==================== -->

    <section style="padding-top: 20px; padding-bottom: 20px">
      <div class="container">
        <h1>New data length is the same</h1>
        <hr />
        <p>
          Let's start with the most common type of axis: the linear axis.
          Basically, the idea is to map a numeric variable to the axis. It is
          used in most of chart types, like
          <a href="../scatter.html">scatterplot</a> or
          <a href="../histogram.html">histogram</a>.
        </p>
        <p>
          Here is the Javascript code allowing to add a linear axis in a div
          that has the id 'res'.
        </p>

        <div>
          <pre
            class="language-js"
          ><code id="code-basic-linear" contenteditable="true"><xmp>// create svg element
// Create a svg area
var svg = d3.select("#res")
  .append("svg")
    .attr("width", 1000)

// Create 2 datasets
var data1 = [50, 100, 150]
var data2 = [70, 280, 600]

// Plot the first dataset
// Here I use enter because I go from 0 circles to 3 circles --> I need to add 3!
svg
  .selectAll("myCircles")
  .data(data1)
  .enter()
  .append("circle")
    .attr("cx", function(d){return(d)})
    .attr("cy", 100)
    .attr("r", 20)

// Now change to second dataset
// I still have 3 circles. So no need to enter() or exit()
svg
  .selectAll("circle")
  .data(data2)
  .transition()
  .duration(4000)
  .attr("cx", function(d){return(d)})

</xmp></code></pre>
        </div>

        <div id="res"></div>
      </div>
    </section>

    <script>
      // Read the JS fragment at the beginning. Read it again if it changes
      myJSParserShort("code-basic-linear");
      document
        .getElementById("code-basic-linear")
        .addEventListener("input", function () {
          d3.select("#res").html("");
          myJSParser("code-basic-linear", "result");
        });
    </script>

    <!-- ================================================================================= -->

    <!-- ==================== MORE VALUES ==================== -->

    <section style="padding-top: 20px; padding-bottom: 20px">
      <div class="container">
        <h1>More values in new dataset</h1>
        <hr />
        <p>
          If I don't change the code, the fourth circle does not appear --> d3
          cannot automatically create a new circle.
        </p>
        <p>I need to use enter() once again to do so</p>

        <div>
          <pre
            class="language-js"
          ><code id="code_ordinal_demo" contenteditable="true"><xmp>// Create a svg area
        var svg = d3.select("#ordinal_demo")
          .append("svg")
            .attr("width", 1000)

        // Create 2 datasets
        var data1 = [50, 100, 150]
        var data2 = [70, 280, 600, 800]

        // Plot the first dataset
        // Here I use enter because I go from 0 circles to 3 circles --> I need to add 3!
        svg
          .selectAll("myCircles")
          .data(data1)
          .enter()
          .append("circle")
            .attr("cx", function(d){return(d)})
            .attr("cy", 100)
            .attr("r", 20)

        // Now change to second dataset

        // First add new elements at cx=0
        svg
          .selectAll("circle")
          .data(data2)
          .enter()
          .append("circle")
            .attr("cx", 0)
            .attr("cy", 100)
            .attr("r", 20)
            .attr("opacity", 0.2)

        // I first modify the 3 circle that were present before:
        svg
          .selectAll("circle")
          .data(data2)
          .transition()
          .duration(4000)
          .attr("cx", function(d){return(d)})

        // Then I add the new point at cx=:
        svg
          .selectAll("circle")
          .data(data2)
          .enter()
          .transition()
          .duration(4000)
          .attr("cx", function(d){return(d)})


</xmp></code></pre>
        </div>

        <div id="ordinal_demo"></div>
      </div>
    </section>

    <script>
      // Read the JS fragment at the beginning. Read it again if it changes
      myJSParserShort("code_ordinal_demo");
      document
        .getElementById("code_ordinal_demo")
        .addEventListener("input", function () {
          d3.select("#ordinal_demo").html("");
          myJSParserShort("code_ordinal_demo");
        });
    </script>

    <!-- ================================================================================= -->

    <!-- ==================== SAME WITH MERGE ==================== -->

    <section style="padding-top: 20px; padding-bottom: 20px">
      <div class="container">
        <h1>IDEM USING MERGE</h1>
        <hr />
        <p>
          If I don't change the code, the fourth circle does not appear --> d3
          cannot automatically create a new circle.
        </p>
        <p>I need to use enter() once again to do so</p>

        <div>
          <pre
            class="language-js"
          ><code id="code_merge_demo" contenteditable="true"><xmp>// Create a svg area
        var svg = d3.select("#merge_demo")
          .append("svg")
            .attr("width", 1000)

        // Create 2 datasets
        var data1 = [50, 100, 150]
        var data2 = [70, 280, 600, 800]

        // Plot the first dataset
        // Here I use enter because I go from 0 circles to 3 circles --> I need to add 3!
        svg
          .selectAll("myCircles")
          .data(data1)
          .enter()
          .append("circle")
            .attr("cx", function(d){return(d)})
            .attr("cy", 100)
            .attr("r", 20)

        // Now change to second dataset

        // Create an update selection:
        var u = svg
          .selectAll("circle")
          .data(data2)

        // Now I want to apply modif to both the previous selection AND the enter selection:
        u.enter()
          .append("circle")
          .merge(u)  // --> Merge function allows to apply to both selection and enter.
          .transition()
          .delay(1000)
          .duration(6000)
            .attr("cx", function(d){return(d)})
            .attr("cy", 100)
            .attr("r", 40)

        u.exit().remove();




</xmp></code></pre>
        </div>

        <div id="merge_demo"></div>
      </div>
    </section>

    <script>
      // Read the JS fragment at the beginning. Read it again if it changes
      myJSParserShort("code_merge_demo");
      document
        .getElementById("code_merge_demo")
        .addEventListener("input", function () {
          d3.select("#merge_demo").html("");
          myJSParserShort("code_merge_demo");
        });
    </script>

    <!-- ================================================================================= -->

    <!-- ==================== SCALE BAND ==================== -->

    <section style="padding-top: 20px; padding-bottom: 20px">
      <div class="container">
        <h1>Less values in new data</h1>
        <hr />
        <p>
          The scaleBand() function is ideal to build categorical axis. It is
          thus useful for common charts like
          <a href="../barplot.html">barplot</a> or
          <a href="../boxplot.html">boxplot</a>.
        </p>
        <p>
          Here is the Javascript code allowing to add a categoric axis in a div
          that has the id 'res'.
        </p>

        <div>
          <pre
            class="language-js"
          ><code id="code_band_demo" contenteditable="true"><xmp>// Create a svg area
        var svg = d3.select("#band_demo")
          .append("svg")
            .attr("width", 1000)

        // Create 2 datasets
        var data1 = [50, 100, 150]
        var data2 = [70, 280]

        // Plot the first dataset
        // Here I use enter because I go from 0 circles to 3 circles --> I need to add 3!
        svg
          .selectAll("myCircles")
          .data(data1)
          .enter()
          .append("circle")
            .attr("cx", function(d){return(d)})
            .attr("cy", 100)
            .attr("r", 20)
            .style("fill", "green")

            // Now change to second dataset
            // I still have 3 circles. So no need to enter() or exit()
            svg
              .selectAll("circle")
              .data(data2)
              .transition()
              .duration(4000)
              .attr("cx", function(d){return(d)})
              // If I stop here, the 3rd circle just does not move.
              // I have to delete it:

            // Delete last point:
            svg
              .selectAll("circle")
              .data(data2)
              .exit()
              .transition()
              .duration(1000)
              .style("opacity", 0)

</xmp></code></pre>
        </div>

        <div id="band_demo"></div>

        <script>
          // Read the JS fragment at the beginning. Read it again if it changes
          myJSParserShort("code_band_demo");
          document
            .getElementById("code_band_demo")
            .addEventListener("input", function () {
              d3.select("#band_demo").html("");
              myJSParserShort("code_band_demo");
            });
        </script>

        <p>
          The scaleBand has a few properties that are very handy when plotting
          groups. See below the padding argument
        </p>

        <div>
          <pre
            class="language-js"
          ><code id="code_band_demo2" contenteditable="true"><xmp>// create svg element
var svg = d3.select("#band_demo2")
  .append("svg")
  .attr("width", 1000)
  .attr("height", 300)

// Create the scale
var names = ["A", "B", "C", "D", "E"]
var x = d3.scaleBand()
  .domain(names)         // This is what is written on the Axis: from 0 to 100
  .range([100, 800])     // This is where the axis is placed: from 100 px to 800px
  .padding([0.8])       // Goes between 0 and 1. Default is 0

// Draw the axis
svg
  .append("g")
  .attr("transform", "translate(0,250)")      // This controls the vertical position of the Axis
  .call(d3.axisBottom(x));

// Add bars
svg.selectAll("bars")
  .data(names)
  .enter()
  .append("rect")
    .attr("x", function(d){ return x(d) })
    .attr("y",100)
    .attr("height", 150)
    .attr("width", x.bandwidth() )

</xmp></code></pre>
        </div>

        <div id="band_demo2"></div>

        <script>
          // Read the JS fragment at the beginning. Read it again if it changes
          myJSParserShort("code_band_demo2");
          document
            .getElementById("code_band_demo2")
            .addEventListener("input", function () {
              d3.select("#band_demo2").html("");
              myJSParserShort("code_band_demo2");
            });
        </script>
      </div>
    </section>

    <!-- ================================================================================= -->

    <!-- ==================== VERTICAL AXIS ==================== -->

    <section style="padding-top: 20px; padding-bottom: 20px">
      <div class="container">
        <h1>Making the axis vertical</h1>
        <hr />
        <p>All the scale described above can be set vertically.</p>

        <div>
          <pre
            class="language-js"
          ><code id="code-vertical" contenteditable="true"><xmp>// create svg element
var svg = d3.select("#vertical")
  .append("svg")
    .attr("width", 1000)
    .attr("height", 300)

// Create the scale
var y = d3.scaleLinear()
    .domain([0, 100])         // This is what is written on the Axis: from 0 to 100
    .range([290, 10]);         // Note it is reversed

// Draw the axis
svg
  .append("g")
  .attr("transform", "translate(50,0)")      // This controls the vertical position of the Axis
  .call(d3.axisLeft(y));</xmp></code></pre>
        </div>

        <div id="vertical"></div>
      </div>
    </section>

    <script>
      // Read the JS fragment at the beginning. Read it again if it changes
      myJSParserShort("code-vertical");
      document
        .getElementById("code-vertical")
        .addEventListener("input", function () {
          d3.select("#vertical").html("");
          myJSParserShort("code-vertical");
        });
    </script>

    <!-- ================================================================================= -->

    <!-- ==================== ROTATE ==================== -->

    <section style="padding-top: 20px; padding-bottom: 20px">
      <div class="container">
        <h1>Rotate and custom axis labels</h1>
        <hr />
        <p>
          It is sometimes useful to rotate the labels of an axis, especially
          when this labels are quite long.
        </p>

        <div>
          <pre
            class="language-js"
          ><code id="code-rotate" contenteditable="true"><xmp>// create svg element
var svg = d3.select("#rotate")
  .append("svg")
    .attr("width", 1000)
    .attr("height", 300)

// Create the scale
var x = d3.scaleBand()
    .domain(["Long name", "Another One", "Here", "And this is", "The end", "ouuuu", "not yet"])         // This is what is written on the Axis: from 0 to 100
    .range([0, 800]);         // Note it is reversed

// Draw the axis
svg
  .append("g")
  .attr("transform", "translate(100,100)")      // This controls the rotate position of the Axis
  .call(d3.axisBottom(x))
  .selectAll("text")
    .attr("transform", "translate(-10,10)rotate(-45)")
    .style("text-anchor", "end")
    .style("font-size", 20)
    .style("fill", "#69a3b2")
</xmp></code></pre>
        </div>

        <div id="rotate"></div>
      </div>
    </section>

    <script>
      // Read the JS fragment at the beginning. Read it again if it changes
      myJSParserShort("code-rotate");
      document
        .getElementById("code-rotate")
        .addEventListener("input", function () {
          d3.select("#rotate").html("");
          myJSParserShort("code-rotate");
        });
    </script>

    <!-- ================================================================================= -->

    <!-- ============================ RELATED BLOCKS ============================ -->

    <section
      id="contact"
      class="bg-light"
      style="padding-top: 70px; padding-bottom: 70px"
    >
      <div class="container">
        <div class="row">
          <div
            class="col-lg-5 text-center .align-middle"
            style="border-right: solid"
          >
            <div style="display: table; height: 150px; overflow: hidden">
              <div style="display: table-cell; vertical-align: middle">
                <h2 class="section-heading text-uppercase" style="color: black">
                  Related blocks
                </h2>
              </div>
            </div>
          </div>
          <div class="col-lg-5">
            <div style="display: table; height: 150px; overflow: hidden">
              <div style="display: table-cell; vertical-align: middle">
                <ul>
                  <li>
                    <i>add border to svg container in d3 - </i
                    ><a href="http://bl.ocks.org/AndrewStaroscik/5222370"
                      >link</a
                    >
                  </li>
                  <br />
                  <li>
                    <i>Multiple Simple graphs on one page - </i
                    ><a href="http://bl.ocks.org/d3noob/5987480">link</a>
                  </li>
                  <br />
                  <li>ll</li>
                </ul>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>

    <!-- ============================ CONTACT SECTION ============================ -->

    <!-- ANCHOR -->
    <a name="contactanchor"></a>

    <section id="contact" class="bg" style="background-color: white">
      <div class="container">
        <div class="row">
          <div class="col-lg-2 text-center"></div>
          <div class="col-lg-8 text-center">
            <br /><br /><br />
            <h2 class="section-heading text-uppercase" style="color: black">
              Contact
            </h2>
            <p>
              This document is a work in progress analysis by Yan Holtz. Any
              feedback is highly encouraged. You can fill an issue on
              <a href="https://github.com/holtzy/data_to_viz">Github</a>, drop
              me a message on
              <a href="https://twitter.com/R_Graph_Gallery">Twitter</a>, or send
              an email pasting <a href="">yan.holtz.data</a> with
              <a href="">gmail.com</a>.
            </p>
            <div style="text-align: center">
              <a
                class="btn btn-primary btn-xl text-uppercase js-scroll-trigger"
                href="https://github.com/holtzy"
                >Github</a
              >
              <a
                class="btn btn-primary btn-xl text-uppercase js-scroll-trigger"
                href="https://twitter.com/R_Graph_Gallery"
                >Twitter</a
              >
            </div>
          </div>
        </div>
      </div>
    </section>

    <!-- ============================ FOOTER SECTION ============================ -->
    <footer class="bg-light">
      <div class="container">
        <div class="row">
          <div class="col-md-4">
            <span class="copyright"
              >Copyright &copy; the d3 graph gallery 2018</span
            >
          </div>
          <div class="col-md-4">
            <ul class="list-inline social-buttons">
              <li class="list-inline-item">
                <a href="https://twitter.com/R_Graph_Gallery">
                  <i class="fa fa-twitter"></i>
                </a>
              </li>
              <li class="list-inline-item">
                <a href="https://github.com/holtzy">
                  <i class="fa fa-github"></i>
                </a>
              </li>
              <li class="list-inline-item">
                <a href="https://www.linkedin.com/in/yan-holtz-2477534a/">
                  <i class="fa fa-linkedin"></i>
                </a>
              </li>
            </ul>
          </div>
          <div class="col-md-4">
            <ul class="list-inline quicklinks">
              <li class="list-inline-item">
                <a href="#">Privacy Policy</a>
              </li>
              <li class="list-inline-item">
                <a href="#">Terms of Use</a>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </footer>

    <!-- ============================ -->

    <!-- ============================ JAVASCRIPT SECTION ============================ -->

    <!-- Bootstrap core JavaScript -->
    <script src="../vendor/bootstrap/js/bootstrap.bundle.min.js"></script>

    <!-- Plugin JavaScript -->
    <!--<script src="../vendor/jquery-easing/jquery.easing.min.js"></script> -->

    <!-- Contact form JavaScript -->
    <script src="../js/jqBootstrapValidation.js"></script>

    <!-- Custom scripts for this template -->
    <script src="../js/agency.min.js"></script>

    <!-- Activate the bootstrap tooltip, must be after jQuery load -->
    <script>
      $(function () {
        $('[data-toggle="tooltip"]').tooltip();
      });
    </script>

    <!-- Function to download the content of the div -->
    <script>
      function download() {
        var a = document.body.appendChild(document.createElement("a"));
        a.download = "export.html";
        var command = document.getElementById("code").innerHTML;
        command = command.replace(/<\/?span[^>]*>/g, "");
        a.href = "data:html" + command;
        a.click(); // Trigger a click on the element
      }
    </script>

    <!-- Function to download the graphic as png automatically -->
    <!--     <script>
        html2canvas($('#content'),
        {
          onrendered: function (canvas) {
            var a = document.createElement('a');
            // toDataURL defaults to png, so we need to request a jpeg, then convert for file download.
            a.href = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
            a.download = 'somefilename.jpg';
            a.click();
          }
        });
    </script> -->
  </body>
</html>
